#include "TCPManager.h"
#include <WiFi.h>
#include <WiFiClient.h>
#include <ArduinoJson.h>
#include "DataModels.h"

namespace TCPManager
{

    void fetchData()
    {
        if (WiFi.status() != WL_CONNECTED)
        {
            Serial.println("WiFi 未连接");
            return;
        }

        WiFiClient client;
        if (!client.connect(TCPManager::TCP_HOST.c_str(), TCPManager::TCP_PORT))
        {
            Serial.println("TCP 连接失败");
            return;
        }

        Serial.println("TCP 已连接，等待数据...");
        // 打印远程服务器 IP
        IPAddress remoteIp = client.remoteIP();
        Serial.print("已连接到服务器 IP: ");
        Serial.println(remoteIp);
        Serial.print("端口: ");
        Serial.println(TCPManager::TCP_PORT);

        String payload;
        unsigned long start = millis();
        while (millis() - start < TCP_RECEIVE_TIMEOUT_MS)
        {
            while (client.available())
            {
                char c = client.read();
                payload += c;
            }
            if (payload.length() > 0)
                break;
            delay(5);
        }
        client.stop();

        if (payload.length() == 0)
        {
            Serial.println("未收到数据");
            return;
        }

        Serial.println("收到数据:\n" + payload);

        DynamicJsonDocument doc(8 * 1024);
        DeserializationError error = deserializeJson(doc, payload);
        if (error)
        {
            Serial.print("解析 JSON 失败: ");
            Serial.println(error.c_str());
            return;
        }

        DataModels::WeatherData &weather = DataModels::weather;

        // ---------------- lunar 数据 ----------------
        JsonObject l = doc["lunar"];
        DataModels::lunar.lmonthname = l["lmonthname"] | "";
        DataModels::lunar.lunarday = l["lunarday"] | "";
        DataModels::lunar.gregoriandate = l["gregoriandate"] | "";
        DataModels::lunar.festival = l["festival"] | "";

        // ---------------- weather 主对象 ----------------
        JsonObject w = doc["weather"];
        weather.text = w["text"] | "";
        weather.tempToday = w["tempToday"] | "";
        weather.tempTomorrow = w["tempTomorrow"] | "";

        // ---------------- 未来12小时温度 ----------------
        JsonArray forecast_hours = w["temperatureNext12Hours"];
        for (int i = 0; i < 12; i++)
        {
            if (i < forecast_hours.size())
                weather.temperatureNextHours[i] = forecast_hours[i].as<String>();
            else
                weather.temperatureNextHours[i] = "--";
        }

        // ---------------- 三项指数提示 ----------------
        JsonArray tipsArr = w["tips"];
        for (int i = 0; i < 3; i++)
        {
            if (i < tipsArr.size())
                weather.tips[i] = tipsArr[i].as<String>();
            else
                weather.tips[i] = "";
        }

        // ---------------- 输出 ----------------
        Serial.println("天气数据解析完成:");
        Serial.println("文本描述: " + weather.text);
        Serial.println("今日温度: " + weather.tempToday);
        Serial.println("明日温度: " + weather.tempTomorrow);
        Serial.print("未来12小时温度: ");
        for (int i = 0; i < 12; i++)
        {
            Serial.print(weather.temperatureNextHours[i] + " ");
        }
        Serial.println();
        Serial.println("指数提示:");
        for (int i = 0; i < 3; i++)
        {
            Serial.println(weather.tips[i]);
        }

        Serial.println("农历数据:");
        Serial.println("公历日期: " + DataModels::lunar.gregoriandate);
        Serial.println("农历月份: " + DataModels::lunar.lmonthname);
        Serial.println("农历日: " + DataModels::lunar.lunarday);
        Serial.println("节日: " + DataModels::lunar.festival);
    }
}